package com.wap.framework.admin.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.wap.framework.model.Image;
import com.wap.framework.service.ImageService;

public class ImageManagerAction extends DispatchAction {
	
	private ImageService imageService;
	
	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}
	
	@SuppressWarnings("unchecked")
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String currentPage = request.getParameter("currentPage");
		if(currentPage == null || "".equals(currentPage)) {
			currentPage = "1";
		}		
		
		List<Object> result = imageService.listImages(Integer.valueOf(currentPage));			
		request.setAttribute("images", (List<Image>)result.get(0));
		request.setAttribute("pageHelper", result.get(1));
		return mapping.findForward("fwd_mgr_image");
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String[] imageIds = request.getParameterValues("id");
		Integer[] ids = (Integer[])ConvertUtils.convert(imageIds, Integer.class);
		imageService.deleteImages(ids);		
		return list(mapping, form, request, response);
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String imageId = request.getParameter("imageId");		
		Image image = imageService.editImage(Integer.valueOf(imageId));
		request.setAttribute("image", image);
		return mapping.findForward("fwd_edit_image");
	}
	
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String imageId 		= request.getParameter("imageId");		
		String imageName 	= request.getParameter("imageName");
		String remark 		= request.getParameter("remark");
		String status 		= request.getParameter("status");
		
		Image image = new Image();
		image.setId(Integer.valueOf(imageId));
		image.setImageName(imageName);
		image.setRemark(remark);
		image.setStatus(Integer.valueOf(status));
		
		imageService.updateImage(image);
		
		return list(mapping, form, request, response);
	}
	
	public static void main(String[] args) {
		String[] a = {"1","2"};
		Integer[] b = (Integer[])ConvertUtils.convert(a, Integer.class);
		for(int x : b) {
			System.out.println(x);
		}
	}
}
